﻿using Confluent.Kafka;
using Mercury.Business.IRepositories;
using Mercury.Core.Configuration;
using Mercury.Entity.DomainModels;
using Microsoft.AspNetCore.SignalR;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace Mercury.WebApi.Controllers.Hubs
{
    public class HomePageMessage
    {
        public static ConcurrentDictionary<string, dynamic> Connection = new ConcurrentDictionary<string, dynamic>();
        private readonly INotificationFormRepository _repository;
        private readonly IHubContext<HomePageMessageHub> _hub;

        public HomePageMessage(INotificationFormRepository repository, IHubContext<HomePageMessageHub> hub)
        {
            _repository = repository;
            _hub = hub;
        }
        public async Task SendNoticeAction(NotificationForm notice)
        {
            var config = AppSetting.NoticeConfigs?.FirstOrDefault(c => c.Methods == "ReceiveHomePageMessage");
            if (config != null)
            {
                await _hub.Clients.Clients(GetCnnectionIds(config.Users, config.UserType).ToArray()).SendAsync("ReceiveHomePageMessage", new
                {
                    //   username,
                    title = "提示",
                    message = notice.Content,
                    date = DateTime.Now.ToString("yyyy-MM-dd HH:mm:sss")
                });
            }
            else
            {
                await _hub.Clients.All.SendAsync("ReceiveHomePageMessage", new
                {
                    //   username,
                    title = "提示",
                    message = notice.Content,
                    date = DateTime.Now.ToString("yyyy-MM-dd HH:mm:sss")
                });
            }
        }

        private IEnumerable<string> GetCnnectionIds(string username, int type)
        {
            var list = new List<string>();
            foreach (var user in username.Split(new[] { "," }, StringSplitOptions.RemoveEmptyEntries))
            {
                foreach (var item in Connection)
                {
                    if (list.Any(c => c == item.Key))
                        continue;
                    if (type == 1)
                    {
                        if (item.Value.UserName == user)
                            list.Add(item.Key);
                        continue;
                    }
                    else if (type == 0)
                    {
                        if (item.Value.RoleId == user)
                            list.Add(item.Key);
                        continue;
                    }
                }
            }
            return list;
        }
    }
}
